import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined, ExperimentOutlined, CopyOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'
import * as XLSX from 'xlsx';
import useStore from '../../useStore.js'
import { clearCache,useDidCache,useDidRecover ,dropByCacheKey } from 'react-router-cache-route';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_khda_initcolmun } from './use_baseinfo_config.js';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const khda_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_khda_initcolmun)
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();


  useEffect(() => {
    querylist()
    storage[`Pc_khda_list${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_khda_list${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_khda_list_initsize${storage.userid}`] ? setinitSize(storage[`Pc_khda_list_initsize${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  const querylist = async () => {
    setisloading(true)
    let rtdata = await fetchsync_util("/admin/baseinfo/khdalb", 'POST', {}, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)

    });
    setlistdata(dealnullorundenfined(rtdata.resultdata))
    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_khda_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('khda_form')
    setnowroute({route:"/shipSRM/baseinfo/khda_form",title:"客户档案_新增"})
  }
  /**
   * 编辑
   */
  const handleEdit = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
    }
    else {
      storage.pre_khda_item = JSON.stringify({ data: selectedRows[0], type: "edit" })
      dropByCacheKey('khda_form')
      setnowroute({route:"/shipSRM/baseinfo/khda_form",title:"客户档案_编辑"})
    }
  }
  /**
   * 删除
   */
  const handledelete = async () => {
      let rtdata = await fetchsync_util("/admin/baseinfo/delete_khda", 'POST', { selectedRows }, "json")
      rtdata.rtstatus ? querylist() : 1
  }
  /**
   * 导出
   */
  const handleExport = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(selectedRows, filtercol, '客户档案')
  }

  const  handleescelimport=async(data)=>{
    let rtdat=await fetchsync_util("/admin/baseinfo/khda_import",'POST',data,"json")
    openNotification_util(rtdat.rtmessage)
    querylist()

  }


  const onImportExcel =  (file) => {

      const { files } = file.target;
      const fileReader = new FileReader();
      fileReader.onload = event => {
        try {
          const { result } = event.target;
          const workbook = XLSX.read(result, { type: 'binary' });
          let data = []; // 存储获取到的数据
          for (const sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          var datastr=JSON.stringify(data);
          datastr=datastr.replace(/客户名称/g, "mc").replace(/编码/g, "bm").replace(/地址/g, "dz").replace(/联系人/g, "lxr").replace(/电话/g, "dh");
         // alert("datastr---"+datastr);

          handleescelimport(JSON.parse(datastr))
            console.log(datastr)
        } catch (e) {
          // 这里可以抛出文件类型错误不正确的相关提示
          console.log('文件类型不正确');
          return;
        }
      };
      // 以二进制方式打开文件
      fileReader.readAsArrayBuffer(files[0]);
    }




  return (
    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>



      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw"
        }}>

          <div style={styleobj.linestyleflex}>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷新</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑 </Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出</Button>




              {/* <span style={{color:"#1287E9",fontSize:"1rem",fontWeight:"bolder",fontStyle:"italic"}}>
                Excel导入客户信息---</span>
                <input type='file' accept='.xlsx, .xls' onChange={onImportExcel} /> */}

          </div>

          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '0.5rem', fontSize: "1.5rem" }}
            onClick={e => setIsModalOpen(true)} />
          {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={"Pc_khda_list"} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage['Pc_khda_list_initsize'] = data; }}
          />}

          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
              <Spin /></div>)
            :
            (<Custom_table_hooks_config tabledata={listdata} tablecolnum={columnarr}
              width={collapsed?"94%":"84%"}
              sfdoubleclick="false" ifhiddencchangeselecttype="true"
              selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
                defaultPageSize={10}
              bordered
              scroll={{ y: 'calc(100vh - 280px)', x: initSize * 1250 }}
              handleselectson={(selectedRows, selectedRowKeys) => {
                setselectedRows(selectedRows)
                setselectedRowKeys(selectedRowKeys)
              }}
            />)
          }
        </div>

      </div>
    </div>
  )
}


export default khda_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


kshcontainer: {
  width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
  color: "black"
},
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem",marginTop:"0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}